//worked on by Ray Zeller
#include "DayParser.h"
#include <iostream>
/*
 * basic algorithm
 * (C) 2002 by Jerry Jenkins
 */
 
const static int	pnDaysBeforeMonth[] = {
		 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
	};
const static string days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
	"Friday", "Saturday"};

DayParser::DayParser(){}
DayParser::DayParser(int n)
:
myNumber(n)
{
	parse();
}


string DayParser::getDayOfWeek()
{
	int	nDayOfWeek;	
	assert( myMonth > 0 && myMonth <= 12 );
	assert( myDay > 0 );
	assert( myDay <= ( pnDaysBeforeMonth[ myMonth+1 ] - pnDaysBeforeMonth[ myMonth ] )
		|| ( myMonth == 2 && myDay == 29 && isLeapYear(myYear) )
		);
	
	/* the day of Jan 1, nYear */
	nDayOfWeek = 6 + myYear % 7 + countOfFeb29(myYear) % 7 + 14;/* + 14 : makes nDayOfWeek >= 0 */
	
	/* the day of nMonth 1, nYear */
	nDayOfWeek += pnDaysBeforeMonth[ myMonth ];
	if( myMonth > 2 && isLeapYear(myYear) ) nDayOfWeek++;
	
	/* the day of nMonth nDay, nYear */
	nDayOfWeek += myDay - 1;
	nDayOfWeek %= 7;
	
	return days[nDayOfWeek];
}

/*
 *	Count of days, which is Feb 29, from Jan 1, 0 to Jan 1, nYear
 *	There is no Feb 29 between Jan 1, 0 and Jan 1, -3, one between Jan 1, 0 and Jan 1, -4
 *	one between Jan 1, 0 and Jan 1, 3 AD, one between Jan 1, 0 and Jan 1, 4
 */
int	DayParser::countOfFeb29( int nYear )
{
	int		nCount = 0;
	if( nYear > 0 ) {
		nCount = 1;	/* Year 0 is a leap year */
		nYear--;/* Year nYear is not in the period */
	}
	nCount += nYear / 4 - nYear / 100 + nYear / 400;

	return nCount;
}

bool DayParser::isLeapYear( int nYear )
{
	if( nYear % 4 != 0 )	return false;
	if( nYear % 100 != 0 )	return true;
	return ( nYear % 400 == 0 );
}

void DayParser::parse(){
	int year;
	int month;
	int day;
	stringstream ss1, d, y, m;
	string s2;
	ss1 << myNumber;
	s2=ss1.str();
	m<<s2.substr(4,2);
	m>>month;
	d<<s2.substr(6,2);
	d>>day;
	y<<s2.substr(0,4);
	y>>year;	
	
	myYear=year;
	myMonth=month;
	myDay=day;
}

DayParser::~DayParser()
{
}
